package org.ucas.kgraph.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.ucas.kgraph.dao.AccountDao;
import org.ucas.kgraph.dao.RelationDao;
import org.ucas.kgraph.dao.RoleDao;
import org.ucas.kgraph.dao.SchemDao;
import org.ucas.kgraph.dto.GraphDto;
import org.ucas.kgraph.dto.ListDto;
import org.ucas.kgraph.entity.Account;
import org.ucas.kgraph.entity.Perm;
import org.ucas.kgraph.entity.Relation;
import org.ucas.kgraph.entity.RelationType;
import org.ucas.kgraph.entity.Role;
import org.ucas.kgraph.entity.Schem;
import org.ucas.kgraph.entity.Term;
import org.ucas.kgraph.entity.TermGraph;
import org.ucas.kgraph.utils.exception.BadRequestException;
import org.ucas.kgraph.utils.exception.ConflictException;
import org.ucas.kgraph.utils.exception.ForbiddenException;
import org.ucas.kgraph.utils.exception.NotFoundException;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Transactional
@Service
public class RoleService {

  @Autowired
  private RoleDao roleDao;

  @Autowired
  private AccountDao accountDao;

  public List<Role> listRoleAll() {
	 return roleDao.findAll();
  }



  public void newRole(Role role) {
	// TODO Auto-generated method stub
	  if(role.getPermsName()==null) throw BadRequestException.Perm_Defect;
	  if(roleDao.findByName(role.getName()).size()!=0){
		  System.out.println("==============="+roleDao.findByName(role.getName()).get(0).getName());
		  throw ConflictException.Role_Conflict;
	  }else{
		  roleDao.save(role);
	  }
  }
  public List<Role> findByName(String name) {
	  return roleDao.findByName(name);
  }
  public void save(Role role) {
	  roleDao.save(role);
  }

  public List<Perm> listRolePerms(Long id) {
	// TODO Auto-generated method stub
	  Role role = new Role();
	  role=roleDao.findOne(id);
	  return role.getPermList();
  }



  public Role load(Long id) {
	// TODO Auto-generated method stub
	return roleDao.findOne(id);
  }



  public void delete(Role role) {
	// TODO Auto-generated method stub
	  List<Account> accounts = accountDao.findAll();
	  for(int i=0; i< accounts.size();i++){
		  if(accounts.get(i).getRolesName().toString().equals("["+role.getName()+"]")){
			  throw ConflictException.Role_Conflict;
		  }
	  }
	  roleDao.delete(role);
  }

  
}
